<script setup>
import { ref, onMounted, computed } from 'vue';

// 用户列表数据
const users = ref([]);
const loading = ref(true);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const showAddModal = ref(false);
const showEditModal = ref(false);
const currentUser = ref(null);

// 新增/编辑用户表单
const userForm = ref({
  username: '',
  email: '',
  password: '',
  avatar: ''
});

// 过滤后的用户列表
const filteredUsers = computed(() => {
  let result = users.value;
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) || 
      user.email.toLowerCase().includes(query)
    );
  }
  
  return result;
});

// 分页数据
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredUsers.value.length / pageSize.value);
});

onMounted(() => {
  fetchUsers();
});

// 模拟获取用户列表
const fetchUsers = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    users.value = [
      { id: 1, username: '张三', email: 'zhangsan@example.com', avatar: '/src/assets/1.webp', created_at: '2023-01-15' },
      { id: 2, username: '李四', email: 'lisi@example.com', avatar: '/src/assets/2.webp', created_at: '2023-02-20' },
      { id: 3, username: '王五', email: 'wangwu@example.com', avatar: '/src/assets/3.webp', created_at: '2023-03-10' },
      { id: 4, username: '赵六', email: 'zhaoliu@example.com', avatar: null, created_at: '2023-04-05' },
      { id: 5, username: '钱七', email: 'qianqi@example.com', avatar: null, created_at: '2023-05-18' },
      { id: 6, username: '孙八', email: 'sunba@example.com', avatar: null, created_at: '2023-06-22' },
      { id: 7, username: '周九', email: 'zhoujiu@example.com', avatar: null, created_at: '2023-07-30' },
      { id: 8, username: '吴十', email: 'wushi@example.com', avatar: null, created_at: '2023-08-15' }
    ];
    loading.value = false;
  }, 800);
};

// 打开新增用户模态框
const openAddModal = () => {
  userForm.value = {
    username: '',
    email: '',
    password: '',
    avatar: ''
  };
  showAddModal.value = true;
};

// 打开编辑用户模态框
const openEditModal = (user) => {
  currentUser.value = { ...user };
  userForm.value = {
    username: user.username,
    email: user.email,
    password: '', // 编辑时不显示密码
    avatar: user.avatar
  };
  showEditModal.value = true;
};

// 删除用户
const deleteUser = (userId) => {
  if (confirm('确定要删除该用户吗？')) {
    users.value = users.value.filter(user => user.id !== userId);
  }
};

// 提交新增用户
const submitAddUser = () => {
  // 简单验证
  if (!userForm.value.username || !userForm.value.email || !userForm.value.password) {
    alert('请填写所有必填字段');
    return;
  }
  
  // 模拟添加用户
  const newUser = {
    id: Date.now(),
    ...userForm.value,
    created_at: new Date().toISOString().split('T')[0]
  };
  
  users.value.push(newUser);
  showAddModal.value = false;
};

// 提交编辑用户
const submitEditUser = () => {
  // 简单验证
  if (!userForm.value.username || !userForm.value.email) {
    alert('请填写所有必填字段');
    return;
  }
  
  // 模拟更新用户
  const index = users.value.findIndex(user => user.id === currentUser.value.id);
  if (index !== -1) {
    users.value[index] = {
      ...users.value[index],
      username: userForm.value.username,
      email: userForm.value.email,
      avatar: userForm.value.avatar
    };
    // 如果填写了新密码，则更新密码
    if (userForm.value.password) {
      // 实际项目中应该加密密码
      users.value[index].password = userForm.value.password;
    }
  }
  
  showEditModal.value = false;
};

// 分页控制
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};
</script>

<template>
  <div>
    <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between">
      <div>
        <h2 class="text-2xl font-bold text-gray-900">用户管理</h2>
        <p class="text-gray-600">管理平台的所有用户账号</p>
      </div>
      <div class="mt-3 sm:mt-0 flex items-center">
        <div class="relative rounded-md shadow-sm mr-3">
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <i class="fa fa-search text-gray-400"></i>
          </div>
          <input 
            type="text" 
            v-model="searchQuery"
            class="block w-full rounded-md border-gray-300 pl-10 pr-3 py-2 text-sm placeholder-gray-400 focus:outline-none focus:ring-primary focus:border-primary"
            placeholder="搜索用户名或邮箱"
          >
        </div>
        <button 
          @click="openAddModal"
          class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          <i class="fa fa-plus mr-2"></i> 添加用户
        </button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white shadow overflow-hidden rounded-lg">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                用户名
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                邮箱
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                头像
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                创建时间
              </th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <template v-if="loading">
              <tr v-for="i in 5" :key="i">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-5 bg-gray-200 rounded animate-pulse"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-5 bg-gray-200 rounded animate-pulse"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-10 w-10 bg-gray-200 rounded-full animate-pulse"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="h-5 bg-gray-200 rounded animate-pulse"></div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <div class="flex justify-end space-x-2">
                    <div class="h-8 w-8 bg-gray-200 rounded animate-pulse"></div>
                    <div class="h-8 w-8 bg-gray-200 rounded animate-pulse"></div>
                  </div>
                </td>
              </tr>
            </template>
            <template v-else>
              <tr v-for="user in paginatedUsers" :key="user.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">{{ user.username }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-500">{{ user.email }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <img 
                    v-if="user.avatar" 
                    :src="user.avatar" 
                    alt="Avatar" 
                    class="h-10 w-10 rounded-full object-cover"
                  >
                  <div v-else class="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center text-gray-500">
                    <i class="fa fa-user"></i>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ user.created_at }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button 
                    @click="openEditModal(user)"
                    class="text-primary hover:text-primary/80 mr-3"
                  >
                    编辑
                  </button>
                  <button 
                    @click="deleteUser(user.id)"
                    class="text-red-600 hover:text-red-800"
                  >
                    删除
                  </button>
                </td>
              </tr>
              <tr v-if="paginatedUsers.length === 0">
                <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                  没有找到匹配的用户
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="!loading && totalPages > 1" class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
        <div class="flex-1 flex justify-between sm:hidden">
          <button 
            @click="changePage(currentPage - 1)"
            :disabled="currentPage === 1"
            class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          >
            上一页
          </button>
          <button 
            @click="changePage(currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
          >
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700">
              显示 <span class="font-medium">{{ Math.max(1, (currentPage - 1) * pageSize + 1) }}</span> 到 <span class="font-medium">{{ Math.min(currentPage * pageSize, filteredUsers.length) }}</span> 条，共 <span class="font-medium">{{ filteredUsers.length }}</span> 条结果
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button 
                @click="changePage(currentPage - 1)"
                :disabled="currentPage === 1"
                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              >
                <i class="fa fa-chevron-left"></i>
              </button>
              <button 
                v-for="page in Math.min(5, totalPages)"
                :key="page"
                @click="changePage(page)"
                class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50"
                :class="{ 'bg-primary text-white': currentPage === page }"
              >
                {{ page }}
              </button>
              <button 
                @click="changePage(currentPage + 1)"
                :disabled="currentPage === totalPages"
                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
              >
                <i class="fa fa-chevron-right"></i>
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加用户模态框 -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">添加新用户</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input 
                type="text" 
                v-model="userForm.username"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input 
                type="email" 
                v-model="userForm.email"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
              <input 
                type="password" 
                v-model="userForm.password"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">头像URL</label>
              <input 
                type="text" 
                v-model="userForm.avatar"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                placeholder="可选"
              >
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showAddModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitAddUser"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            添加
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">编辑用户</h3>
        </div>
        <div class="px-6 py-4">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input 
                type="text" 
                v-model="userForm.username"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <input 
                type="email" 
                v-model="userForm.email"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">新密码（留空表示不修改）</label>
              <input 
                type="password" 
                v-model="userForm.password"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                placeholder="留空表示不修改"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">头像URL</label>
              <input 
                type="text" 
                v-model="userForm.avatar"
                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                placeholder="可选"
              >
            </div>
          </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
          <button 
            @click="showEditModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            @click="submitEditUser"
            class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:root {
  --primary-color: #4f46e5;
}

.bg-primary {
  background-color: var(--primary-color);
}

.text-primary {
  color: var(--primary-color);
}

.hover\:text-primary\/80:hover {
  color: rgba(79, 70, 229, 0.8);
}

.hover\:bg-primary\/90:hover {
  background-color: rgba(79, 70, 229, 0.9);
}

.focus\:ring-primary:focus {
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.5);
}

.focus\:border-primary:focus {
  border-color: var(--primary-color);
}

.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}
</style>